<script setup lang="ts">
import {computed, type CSSProperties, nextTick, onActivated, onBeforeUnmount, onMounted, ref} from 'vue';
import {ElTooltip} from 'element-plus'; // 引入 Element Plus 组件
import {devEllipsisTextProps} from "./ellipsisText";
import {devDeepMerge, useConfig} from '@/index';
import { debounce } from 'lodash'

const props = defineProps(devEllipsisTextProps);// 定义组件属性
const container = ref<any>(null); // DOM 引用
const isOverflowing = ref(false); // 是否超出限制
const content = ref('');

const defaultTooltipProps = useConfig().elTooltipProps;

// 计算最终的 tooltip 配置
const tooltipProps = computed(() =>
    devDeepMerge(defaultTooltipProps, props.elTooltipAttrs, {
      _all: ['content'],
    })
);

// 动态样式：根据传入的行数限制展示
const computedStyle = computed<CSSProperties>(() => ({
  display: '-webkit-box',
  WebkitBoxOrient: 'vertical',
  WebkitLineClamp: props.lines,
  overflow: 'hidden',
}));

let observer: MutationObserver | null = null;

// 检查内容是否超出
const checkOverflow = debounce(() => {
  if (container.value) {
    const {scrollHeight, clientHeight} = container.value;
    isOverflowing.value = scrollHeight > clientHeight;
    content.value = container.value?.innerText;
  }else{
    content.value = props.text || '';
  }
  nextTick(() => {
    if (container.value) {
      // 初始化 MutationObserver
      observer = new MutationObserver(onSlotContentChanged);
      // 开始观察 container 内的 DOM 变化
      observer.observe(container.value, {
        childList: true,
        subtree: true,
        characterData: true,
      });
    }
  });
},200);

// 插槽内容变化的回调函数
const onSlotContentChanged = (mutations: MutationRecord[]) => {
  mutations.forEach((mutation) => {
    // 在这里添加自定义的处理逻辑
    checkOverflow();
  });
};

/**
 * 初始化
 */
const init = async () => {
  checkOverflow();
}

onMounted(() => {
  if (props.onMounted && !props.onActivated) {
    init();
  }
})

onActivated(() => {
  if (props.onActivated) {
    init();
  }
})

onBeforeUnmount(() => {
  // 在组件卸载时断开观察器，避免内存泄漏
  if (observer) {
    observer.disconnect();
  }
});

defineOptions({name: 'DevEllipsisText'});

</script>

<template>
  <el-tooltip
      v-if="isOverflowing && content && props.showTooltip"
      :content="content"
      v-bind="tooltipProps"
  >
    <div ref="container" class="dev-ellipsis-container" :style="computedStyle">
      <slot>{{ props.text }}</slot>
    </div>
  </el-tooltip>

  <div
      v-else
      ref="container"
      class="dev-ellipsis-container"
      :style="computedStyle"
  >
    <slot>{{ props.text }}</slot>
  </div>
</template>

<style scoped lang="scss">
.dev-ellipsis-container {
  word-break: break-word;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>




